<template>
  <div class="edit-bg">
    <div class="edit-card">
      <button class="return-btn blue" type="button" @click="onCancel">返回</button>
      <div class="edit-title">{{ isEdit ? '编辑药品' : '新增药品' }}</div>
      <form @submit.prevent="onSubmit">
        <div class="edit-form-row">
          <label class="edit-label">药品分类：</label>
          <select v-model="formData.classification" class="edit-input type-select" required>
            <option value="">请选择</option>
            <option value="甲类">甲类</option>
            <option value="乙类">乙类</option>
            <option value="丙类">丙类</option>
          </select>
        </div>
        <div class="edit-form-row">
          <label class="edit-label">医保中文名称：</label>
          <input v-model="formData.drugName" class="edit-input" required placeholder="请输入医保中文名称" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">商品名：</label>
          <input v-model="formData.tradeName" class="edit-input" placeholder="请输入商品名" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">规格：</label>
          <input v-model="formData.specification" class="edit-input" placeholder="请输入规格" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">单位：</label>
          <input v-model="formData.unit" class="edit-input" placeholder="请输入单位" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">支付标准：</label>
          <button type="button" class="price-btn" @click="decreasePrice">-</button>
          <input v-model.number="formData.paymentStandard" class="edit-input price-input" 
                 style="width: 120px; text-align: center; margin: 0 8px;" 
                 placeholder="0.00" step="0.01" min="0" />
          <button type="button" class="price-btn" @click="increasePrice">+</button>
        </div>
        <div class="edit-form-row">
          <label class="edit-label">生产企业：</label>
          <input v-model="formData.manufacturer" class="edit-input" placeholder="请输入生产企业" />
        </div>
        <div class="edit-form-row">
          <label class="edit-label">备注：</label>
          <textarea v-model="formData.remarks" class="edit-input remark-textarea" placeholder="请输入备注"></textarea>
        </div>
        <div class="edit-actions">
          <button class="edit-btn" type="submit" :disabled="loading">
            {{ loading ? '保存中...' : '保存' }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getDrugById, addDrug, updateDrug } from '@/api/drugs'

const router = useRouter()
const route = useRoute()
const loading = ref(false)

// 表单数据
const formData = reactive({
  drugId: null,
  classification: '',
  drugName: '',
  tradeName: '',
  specification: '',
  unit: '',
  manufacturer: '',
  paymentStandard: 0,
  remarks: ''
})

// 判断是否为编辑模式
const isEdit = computed(() => route.params.id && route.params.id !== 'new')

// 获取药品详情
const fetchDrugDetail = async (id) => {
  try {
    loading.value = true
    const response = await getDrugById(id)
    
    if (response.flag) {
      const drug = response.data
      Object.assign(formData, {
        drugId: drug.drugId,
        classification: drug.classification || '',
        drugName: drug.drugName || '',
        tradeName: drug.tradeName || '',
        specification: drug.specification || '',
        unit: drug.unit || '',
        manufacturer: drug.manufacturer || '',
        paymentStandard: drug.paymentStandard || 0,
        remarks: drug.remarks || ''
      })
    } else {
      ElMessage.error(response.message || '获取药品详情失败')
      router.push('/medical-info/drugs')
    }
  } catch (error) {
    console.error('获取药品详情失败:', error)
    ElMessage.error('获取药品详情失败: ' + (error.message || '网络错误'))
    router.push('/medical-info/drugs')
  } finally {
    loading.value = false
  }
}

// 价格调整
const increasePrice = () => {
  formData.paymentStandard = Number((Number(formData.paymentStandard) + 0.1).toFixed(2))
}

const decreasePrice = () => {
  formData.paymentStandard = Math.max(0, Number((Number(formData.paymentStandard) - 0.1).toFixed(2)))
}

// 表单提交
const onSubmit = async () => {
  // 表单验证
  if (!formData.classification) {
    ElMessage.warning('请选择药品分类')
    return
  }
  if (!formData.drugName.trim()) {
    ElMessage.warning('请输入医保中文名称')
    return
  }

  try {
    loading.value = true
    
    const submitData = {
      ...formData,
      drugName: formData.drugName.trim(),
      tradeName: formData.tradeName?.trim() || '',
      specification: formData.specification?.trim() || '',
      unit: formData.unit?.trim() || '',
      manufacturer: formData.manufacturer?.trim() || '',
      remarks: formData.remarks?.trim() || ''
    }

    let response
    if (isEdit.value) {
      // 编辑模式
      response = await updateDrug(submitData)
    } else {
      // 新增模式
      delete submitData.drugId // 新增时不需要ID
      response = await addDrug(submitData)
    }

    if (response.flag) {
      ElMessage.success(response.message || (isEdit.value ? '修改成功' : '新增成功'))
      router.push('/medical-info/drugs')
    } else {
      ElMessage.error(response.message || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error) {
    console.error('保存药品失败:', error)
    ElMessage.error('保存失败: ' + (error.message || '网络错误'))
  } finally {
    loading.value = false
  }
}

// 取消操作
const onCancel = () => {
  router.push('/medical-info/drugs')
}

// 页面初始化
onMounted(() => {
  if (isEdit.value) {
    // 编辑模式：从API获取数据
    fetchDrugDetail(route.params.id)
  } else {
    // 新增模式：尝试从localStorage获取数据（如果有的话）
    const storedData = localStorage.getItem('editDrug')
    if (storedData) {
      try {
        const parsedData = JSON.parse(storedData)
        // 映射旧字段到新字段
        Object.assign(formData, {
          classification: parsedData.type || parsedData.classification || '',
          drugName: parsedData.name || parsedData.drugName || '',
          tradeName: parsedData.brand || parsedData.tradeName || '',
          specification: parsedData.spec || parsedData.specification || '',
          unit: parsedData.unit || '',
          manufacturer: parsedData.manufacturer || '',
          paymentStandard: parsedData.price || parsedData.paymentStandard || 0,
          remarks: parsedData.remark || parsedData.remarks || ''
        })
        localStorage.removeItem('editDrug')
      } catch (error) {
        console.warn('解析存储的药品数据失败:', error)
      }
    }
  }
})
</script>

<style scoped>
.edit-bg {
  min-height: 100vh;
  background: #f5f6fa;
  width: 100%;
  display: flex;
  align-items: stretch;
  justify-content: stretch;
  padding: 0;
}
.edit-card {
  background: #fff;
  border-radius: 0;
  box-shadow: none;
  padding: 0;
  width: 100%;
  min-width: 0;
  max-width: none;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
}
.edit-title {
  font-size: 28px;
  font-weight: bold;
  color: #222;
  margin: 32px 0 32px 64px;
  text-align: left;
  letter-spacing: 1px;
}
.edit-form-row {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  padding: 0;
}
.edit-label {
  width: 160px;
  color: #34495e;
  font-size: 16px;
  text-align: right;
  margin-right: 12px;
  position: relative;
}
.edit-input {
  flex: 1;
  height: 36px;
  border: 1px solid #d0d5dd;
  border-radius: 4px;
  padding: 0 12px;
  font-size: 15px;
  width: 100%;
}
.edit-input:not(.type-select):not(.price-input) {
  max-width: 600px;
}
.edit-actions {
  margin: 32px 0 0 64px;
  display: flex;
  gap: 18px;
}
.edit-btn {
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 32px;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.return-btn {
  position: absolute;
  top: 24px;
  right: 32px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  height: 36px;
  padding: 0 32px;
  font-size: 16px;
  cursor: pointer;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
}
.return-btn.blue {
  background: #409eff;
  color: #fff;
}
.type-select {
  width: 120px;
  min-width: 80px;
  max-width: 160px;
  padding-right: 24px;
  appearance: auto;
}
.price-input {
  width: 100px !important;
  min-width: 60px;
  max-width: 120px;
  display: inline-block;
}
.price-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #d0d5dd;
  background: #f5f6fa;
  color: #34495e;
  border-radius: 4px;
  font-size: 20px;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin: 0 2px;
  transition: background 0.2s;
}
.price-btn:hover {
  background: #eaf3ff;
}
.remark-textarea {
  min-height: 108px;
  height: 108px;
  resize: vertical;
  font-family: inherit;
}
</style>